<template>
  <div class="components-excel">
    <slot :open="open"></slot>
    <t-dialog
      v-model:visible="show"
      :width="500"
      :header="lang.t('title')"
      destroyOnClose
      :closeOnOverlayClick="false"
      placement="center"
    >
      <template #body>
        <div class="content">
          <t-row :gutter="20">
            <t-col :span="6">
              <div class="bg-box">
                <div class="item wrap">
                  <div class="name">{{ lang.t('total') }}</div>
                  <span>{{ total }}</span>
                </div>
              </div>
            </t-col>
            <t-col :span="6">
              <div class="bg-box">
                <div class="item wrap">
                  <div class="name">{{ lang.t('count') }}</div>
                  <span class="color">{{ count }}</span>
                </div>
              </div>
            </t-col>
          </t-row>
        </div>
      </template>
      <template #footer>
        <t-button theme="primary" v-if="!start" @click="onSubmit">
          {{ lang.t('button') }}
        </t-button>
        <t-progress theme="plump" v-else :percentage="progress" status="active" />
      </template>
    </t-dialog>
  </div>
</template>
<script setup>
  import { ref } from 'vue'
  import app from '@/app'
  import { writeFileXLSX, utils } from 'xlsx';

  const lang = app.lang.space('components.excel')
  const props = defineProps(['total', 'handle'])
  const show = ref(false)
  const start = ref(false)
  const progress = ref(0)
  const count = ref(0)

  const open = () => {
    show.value = true
  }

  const onSubmit = async () => {
    start.value = true
    count.value = 0
    onProgress(0)

    const ws = utils.aoa_to_sheet(await props.handle(onProgress))
    ws['A1'].s = {
      fill: {
        fgColor: { rgb: "FFFF0000" } // 这里的RGB值代表红色加黄色，组合成黄色
      }
    }
    const wb = utils.book_new()
    utils.book_append_sheet(wb, ws, "Sheet1")
    writeFileXLSX(wb, "export.xlsx");

    start.value = false
  }

  // 更新进条度
  const onProgress = (value = 1) => {
    count.value += value
    
    // 计算进度
    progress.value = parseInt(count.value / props.total * 100)
  }
</script>
<style lang="scss">
  @import '@/style/global';

  .components-excel{
    display: inline;

    .bg-box{
      padding: 20px !important;
    }

    .content{
      overflow: hidden;
    }

    .t-dialog{
      background-color: $color-bg;
    }

    .t-transfer__list{
      width: 50%;
    }

    .item{  
      color: $color-title;
      font-size: 16px;
      line-height: 20px;
      
      .name{
        color: $color-body;
        padding-bottom: 10px;
        font-size: 14px;
      }

      span{
        font-weight: bold;
      }

      .color{
        color: $color;
      }
      .error{
        color: $color-error;
      }
    }
  }
</style>